<?php
/**
 * 迭代器模式
 * This file is part of pattern.
 * Author: tangzhou
 * Date: 2016/9/21
 * Time: 17:40
 * File: IIterator.php
 */


abstract class IIterator
{
    abstract public function first();
    abstract public function next();
    abstract public function isDone();
    abstract public function currentItem();
}

class ConcreteIterator extends IIterator
{
    private $arr;
    public $current = 0;

    public function __construct(Array $arr)
    {
        $this->arr = $arr;
    }

    public function first()
    {
        return $this->arr[0];
    }

    public function next()
    {
        $this->current++;
        if ($this->current < count($this->arr)) {
            return $this->arr[$this->current];
        }
        return false;
    }

    public function isDone()
    {
        return $this->current == count($this->arr) ? false : true;
    }

    public function currentItem()
    {
        return $this->arr[$this->current];
    }
}

$arr = array(1,2,3,4,5);
$i = new ConcreteIterator($arr);

while ($i->isDone()) {
    echo $i->currentItem();
    $i->next();
}